package com.woniu.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.util.JwtTokenUtil;
import com.woniu.util.ResponseResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        try {
            //获取请求的参数用户名
            String username = request.getParameter("username");
            //生成Token
            String tokenStr = JwtTokenUtil.createSign(username);
            //定义用于响应输出的结果对象
            ResponseResult<String> success =
                    new ResponseResult(tokenStr,"登录成功",200);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            //利用jackon转json串的方法
            writer.write(new ObjectMapper().writeValueAsString(success));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
